package com.weixing.mall.provider.support.excel;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.provider.model.vo.AfterSaleVo;
import com.weixing.mall.util.SKUUtils;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

/**
 * 售后订单管理导出
 */
public class AfterSaleOrderExcalDownLoad {

    public static void ExcalDownload(List<AfterSaleVo> list,HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = "售后订单管理列表"+ DateUtil.now();
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AfterSaleED.class).sheet("sheet1").doWrite(loadDataAndUrl(list));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 封装数据并将url替换为全路径、订单来源转换
     * @param list
     * @return
     */
    private static List<AfterSaleED> loadDataAndUrl(List<AfterSaleVo> list) throws Exception {
        List<AfterSaleED> listData = Lists.newArrayList();
        for (AfterSaleVo asv : list) {
            AfterSaleED ased = new AfterSaleED();
            BeanUtils.copyProperties(asv, ased);
            if(asv.getImg() != null){
                ased.setImg(new URL(GlobalConstant.IMG_PATH_URL + asv.getImg()+GlobalConstant.IMG_PATH_URL_SUFFIX));
            }
            if (asv.getOrderType() != null) {
                ased.setOrderType(asv.getOrderType().getDesp());
            }
            if(asv.getAfterSaleType() != null){
                ased.setAfterSaleType(asv.getAfterSaleType().getDesp());
            }
            if(asv.getOrderStatus() != null){
                ased.setOrderStatus(asv.getOrderStatus().getDesp());
            }
            if(asv.getStatus() != null){
                ased.setStatus(asv.getStatus().getDesp());
            }
            if(ObjectUtil.isNotEmpty(asv.getProductSkuDesp())){
                ased.setColor(SKUUtils.color2(asv.getProductSkuDesp()));
                ased.setSize(SKUUtils.size2(asv.getProductSkuDesp()));
            }
            if(asv.getSysTag() != null){
                ased.setSysTag(asv.getSysTag().getDesp());
            }
            listData.add(ased);
        }
        return listData;
    }
}
